using System.Windows;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using WpfClient.Application.ViewModels;

namespace WpfClient.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, IRecipient<OpenWindowMessage>
    {
        private readonly IServiceProvider _serviceProvider;

        public MainWindow(MainViewModel viewModel, IServiceProvider serviceProvider)
        {
            InitializeComponent();
            DataContext = viewModel;
            _serviceProvider = serviceProvider;

            // 注册消息接收
            WeakReferenceMessenger.Default.Register(this);
        }

        public void Receive(OpenWindowMessage message)
        {
            switch (message.WindowName)
            {
                case "UserManagement":
                    OpenUserManagementWindow();
                    break;
            }
        }

        private void OpenUserManagementWindow()
        {
            try
            {
                var userManagementWindow = _serviceProvider.GetRequiredService<UserManagementWindow>();
                userManagementWindow.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开用户管理窗口失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            // 取消注册消息接收
            WeakReferenceMessenger.Default.Unregister<OpenWindowMessage>(this);
            base.OnClosed(e);
        }
    }
}